/**
 * by gsunwu@foxmail.com
 * 工具类
 */
import java.io.*;

public class Utils {

    public static void WriteDataToFile(String str,String type) throws IOException {


        FileWriter fw = null;
        try {
            File f = null;
            //如果文件存在，则追加内容；如果文件不存在，则创建文件
            if(type.equals("MID")){
                 f = new File(Config.MACFILE);
            }else if(type.equals("OUTPUT")){
                 f = new File(Config.OUTPUT);
            }
            fw = new FileWriter(f, true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        PrintWriter pw = new PrintWriter(fw);
        pw.print(str);
        pw.flush();
        try {
            fw.flush();
            pw.close();
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    /* @return String 16进制串
     * @param binary 需要转换成16进制的2进制串
     */
    public static String binaryToHex(String binary) {
        String hex = "";
        String fourBits = "";
        int oneBit = 0;
        int length = binary.length() / 4;
        for (int i = 0; i < length; ++i) {
            fourBits = binary.substring(0, 4);
            oneBit = Integer.parseInt(fourBits, 2);
            hex += Integer.toHexString(oneBit);
            binary = binary.substring(4);
        }
        return hex;
    }
    /**
     * 16进制转换成为string类型字符串
     * @param s
     * @return
     */
    public static String hex2String(String s) {
        if (s == null || s.equals("")) {
            return null;
        }
        s = s.replace(" ", "");
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "UTF-8");
            new String();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }
}
